package cn.net.dpi.core.aspect;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 日志记录
 *
 * @author DPI160(peijinxu)
 * @date 2022/5/16 15:50
 */
@Slf4j
@Aspect
public class LogAspect {


    /**
     * 这里把切点切再controller（web）层下的每个方法
     */
    @Pointcut("execution(public * cn.net.dpi.controller.*.*(..)) && !@annotation(cn.net.dpi.core.annotation.ApiClearLog)")
    public void log() {
        //default is
    }


    /**
     * 执行com.javayihao.myweb.controller下所有的方法之前执行这个方法
     * 获取要记录的url ip 请求的方法 以及请求时候所带的参数
     */
    @Around("log()")
    @SuppressWarnings("all")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String url = attributes.getRequest().getServletPath();
        //参数
        Object[] args = joinPoint.getArgs();

        //调用自己封装的对象
        if (log.isDebugEnabled()) {
            String requestStr = "";
            if (args.length > 0) {
                requestStr = JSONUtil.toJsonStr(args);
            }
            log.debug("api request url:{} request:{}", url, requestStr);
        } else {
            log.info("api request url:{}", url);
        }

        Object result = null;
        try {
            result = joinPoint.proceed();
        } finally {
            long time = System.currentTimeMillis() - startTime;
            if (log.isDebugEnabled()) {
                log.debug("api reponse url:{} time:{} result:{}", url, time, result != null ? JSONUtil.toJsonStr(result) : "");
            } else {
                log.info("api reponse url:{} time:{}", url, time);
            }
        }
        return result;
    }


}
